#!/usr/bin/env python3
# -*- coding:utf-8 -*-

"""
1、过滤postgresql.conf里的一些重复配置。并得到重复位置、去重结果。
2、对比两个postgresql.conf的差异


RUN：
    python3 script postgresql.conf1  [ postgresql.conf2 ]

"""

import sys


def ad_duplicate(conf):
    with open(conf, 'r') as f:
        lines = f.readlines()
    pos = {}
    res = {}
    linekv = []
    
    for i, line in enumerate(lines):
        if line.startswith('#') or line.strip() == '':
            linekv.append(['', line])
            continue
    
        name = line.split('=')[0].strip()
        if pos.get(name) is None:
            pos[name] = []
        pos[name].append(i)
        res[name] = line
        linekv.append([name, line])
        
    print('################################ {} ################################'.format(conf))
    print('#------------------------- DUPLICATE POS -------------------------')
    for k,v in pos.items():
        if len(v) > 1:
            print(k, v)
    
    print('#------------------------- AD DUPLICATION RES -------------------------')
    for k,v in res.items():
        print(v, end='')
    
    return pos, res, linekv


def diff_merge_conf(conf1, res1, linekv1, conf2, res2, linekv2):
    print('################################ DIFF {0} - {1} ################################'.format(conf1, conf2))
    
    def _merge(target_dict, target_k, newval):
        for lkv in target_dict:
            if lkv[0] == target_k:
                lkv[1] = newval
                return
    
    
    for k,v in res1.items():
        if res2.get(k) is None:
            print('RIGHT NULL for ', k)
            _merge(linekv1, k, '')
        elif res2[k] != v:
            print('DIFFERENCE between', k)
            _merge(linekv1, k, res2[k])
        else:
            print('EQUAL for', k)
    
    needadd = []
    for k,v in res2.items():
        if res1.get(k) is None:
            print('LEFT NULL for', k)
            needadd.append(v)
    
    print('################################ MERGE {0} << {1} ################################'.format(conf1, conf2))
    for l in linekv1:
        print(l[1], end='')
    print('# these is new:')
    for l in needadd:
        print(l, end='')


if __name__ == '__main__':
    if len(sys.argv) <= 1:
        print('NOTHING')
        exit()
    
    pos1, res1, linekv1 = ad_duplicate(sys.argv[1])
    if len(sys.argv) == 2:
        exit()
    
    pos2, res2, linekv2 = ad_duplicate(sys.argv[2])
    diff_merge_conf(sys.argv[1], res1, linekv1, sys.argv[2], res2, linekv2)
    
    if len(sys.argv) == 3:
        exit()
    print('ERROR: too many param')

